import React, {useState, useEffect} from 'react';
import {Layout, Menu, Avatar, Dropdown, Badge, Drawer} from 'antd';
import {useDispatch, useSelector} from 'react-redux';
import {DownOutlined, UserOutlined} from '@ant-design/icons';
import styled from 'styled-components';
import {logoutAction} from '../../redux/loginStore/actions';
import {createMenu} from '../../router/treeMenu';
import {useLocation, Outlet, Link, useNavigate} from 'react-router-dom';
import {createWebSocket, closeWebSocket} from '../../components/websocket';
import './index.css';
const {Header, Content, Sider, Footer} = Layout;
const {SubMenu} = Menu;

export default function Headertb() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [avaHeight, setAvaHeight] = useState(0);
  const itemdata = JSON.parse(sessionStorage.getItem("itemKey"));
  const [itemKey, setitemKey] = useState(itemdata || "2");
  const [openKeys, setOpenKeys] = useState([]);
  const [rootSubmenuKeys, setRootSubmenuKeys] = useState([]);
  const [count, setcount] = useState(1);
  const [visible, setVisible] = useState(false);
  // 一级菜单 key 列表
  useEffect(() => {
    let subdata = [];
    for (let i = 1; i < navBtn.length; i++) {
      subdata.push("sub" + i);
    }
    setRootSubmenuKeys(subdata);
  }, []);
  const liftBtn = ({key}) => {
    switch (key) {
      case '1':
        //console.log("查看个人信息");
        break;
      case '2':
        //console.log("修改密码");
        break;
      case '3':
        navigate('/login');
        dispatch(logoutAction());
        // window.sessionStorage.removeItem('initState');
        // window.sessionStorage.removeItem('openKeys');
        window.sessionStorage.removeItem('token');
        // window.sessionStorage.removeItem('itemKey');
        // window.sessionStorage.removeItem('LoginLog');
        break;
      default:
        return key;
    }
  };

  // 初始化获取当前屏幕可用高度
  useEffect(() => {
    const h = window.innerHeight;
    setAvaHeight(h - 64 - 54 - 70);
    window.onresize = function () {
      const h = window.innerHeight;
      setAvaHeight(h - 64 - 54 - 70);
      //页面大小改变
    };
  }, []);
  // useEffect(() => {
  //   let url = 'ws://192.168.200.202:9999'; //服务端连接的url
  //   console.log(createWebSocket(url));
  //   //在组件卸载的时候，关闭连接
  //   return () => {
  //     closeWebSocket();
  //   };
  // });
  
  
  // 头部菜单
  const headMenu = (
    <Menu onClick={liftBtn}>
      <Menu.Item key="1">个人信息</Menu.Item>
      <Menu.Item key="2">修改密码</Menu.Item>
      <Menu.Item key="3">退出</Menu.Item>
    </Menu>
  );
  const navBtn = [
    {
      name: '房间状态',
      component: '/RoomStatus',
      id: 2,
    },
    // {
    //   name: '上传测试',
    //   component: '/upload',
    //   id: 20,
    // },
    {
      name: '菜品管理',
      id: 3,
      children: [
        {
          name: '点餐订单',
          component: '/OrderingOrder',
          id: 4,
        },
        {
          name: '菜单列表',
          component: '/MenuList',
          id: 5,
        },
      ],
    },
    {
      name: '房间管理',
      id: 6,
      children: [
        {
          name: '房间列表',
          component: '/RoomList',
          id: 7,
        },
      ],
    },
  ];
  const showDrawer = () => {
    setVisible(true);
  };

  const onClose = () => {
    setVisible(false);
  };
  const location = useLocation();
  const pageName = () => {
    switch (location.pathname) {
      case '/RoomList':
        return '房间列表';
      case '/MenuList':
        return '菜单列表';
      case '/OrderingOrder':
        return '点餐订单';
      case '/RoomStatus':
        return '房间状态';
      default:
        return '';
    }
  };
  // 处理只展开一个一级菜单
  const onOpenChange = (keys) => {
    //console.log("菜单切换:", keys[keys.length - 1]);
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
      //console.log("下拉菜单", keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
    sessionStorage.setItem("openKeys", JSON.stringify(keys));
  };
  const onSelect = (e) => {
    console.log(e)
    const itemKey = e.key;
    //console.log(itemKey)
    setitemKey(itemKey);
    sessionStorage.setItem("itemKey", JSON.stringify(itemKey));
  };
  return (
    <Layout>
      <Header className="header">
        <div className="logo">朴院梨花溪民宿酒店-后台管理系统</div>
        <div className="dao-hearlift">
          <Badge count={count} size="small" onClick={showDrawer}>
            <Avatar icon={<UserOutlined />} />
          </Badge>
          <Dropdown overlay={headMenu}>
            <div className="haed-user" onClick={(e) => e.preventDefault()}>
              管理员
              <DownOutlined />
            </div>
          </Dropdown>
        </div>
      </Header>
      <Layout>
        <Sider width={250} className="site-layout-background">
          <Menu
          onOpenChange={onOpenChange}
          openKeys={openKeys}
          defaultSelectedKeys={itemKey}
          onSelect={(e) => onSelect(e)}
            mode="inline"
            style={{
              height: avaHeight + 123,
              borderRight: 0,
              overflowY: 'auto',
              width: '100%',
            }}
          >
            {createMenu(navBtn)}
          </Menu>
        </Sider>
        <Layout
          className="layout"
          style={{padding: '15px 15px 15px', height: avaHeight + 123}}
        >
          <div className="pagebox">
            <div className="pageName">{pageName()}</div>
          </div>
          <Content
            className="site-layout-background"
            style={{
              padding: 15,
              margin: 0,
              overflowY: 'auto',
            }}
          >
            <Outlet />
          </Content>
        </Layout>
      </Layout>
      <Drawer
        title="未读消息"
        placement="right"
        onClose={onClose}
        visible={visible}
      >
        <p onClick={()=>{setcount(0);setVisible(false);navigate('/OrderingOrder');}}>您有一条订单待处理(点击查看)</p>
      </Drawer>
    </Layout>
  );
}
